<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文章概括" prop="summary">
        <el-input
          v-model="queryParams.summary"
          placeholder="请输入文章概括"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优先级" prop="level">
        <el-input
          v-model="queryParams.level"
          placeholder="请输入优先级"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="点赞数" prop="pollCount">
        <el-input
          v-model="queryParams.pollCount"
          placeholder="请输入点赞数"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="阅读数" prop="readCount">
        <el-input
          v-model="queryParams.readCount"
          placeholder="请输入阅读数"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评论数" prop="commentCount">
        <el-input
          v-model="queryParams.commentCount"
          placeholder="请输入评论数"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属类别" prop="classify">
        <el-select v-model="queryParams.classifyList" size="small" placeholder="请选择所属类别" @change="handleQuery"
                   clearable multiple>
          <el-option
            v-for="item in classifyEnum"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否展示" prop="hasDeleted">
        <el-select v-model="queryParams.hasDeleted" size="small" placeholder="请选择是否展示数据" @change="handleQuery"
                   clearable>
          <el-option
            v-for="item in hasDeletedEnum"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['blog:article:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['blog:article:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['blog:article:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                :loading="exportLoading"
                @click="handleExport"
                v-hasPermi="['blog:article:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

        <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="ID" align="center" prop="id" v-if="false"/>
          <el-table-column label="标题" align="center" prop="title"/>
          <el-table-column label="文章概括" align="center" prop="summary"/>
          <el-table-column label="文章内容" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-reading"
                @click="lookContent(scope.row.id)"
                v-hasPermi="['blog:content:query']"
              />
            </template>
          </el-table-column>
          <el-table-column label="优先级" align="center" prop="level"/>
          <el-table-column label="点赞数" align="center" prop="pollCount"/>
          <el-table-column label="阅读数" align="center" prop="readCount"/>
          <el-table-column label="评论数" align="center" prop="commentCount"/>
          <el-table-column label="所属类别" align="center" prop="classify"/>
          <el-table-column label="是否展示" align="center" prop="hasDeleted">
            <template slot-scope="scope">
              <el-switch
                class="tableScopeSwitch"
                v-model="scope.row.hasDeleted"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="0"
                :inactive-value="1"
                active-text="开启"
                inactive-text="关闭"
                @change="(status)=>updateHasDeleted(status,scope.row)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="updateContent(scope.row.id)"
                v-hasPermi="['blog:content:edit']"
              >内容编辑
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['blog:article:edit']"
              >修改
              </el-button>
              <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleDelete(scope.row)"
                      v-hasPermi="['blog:article:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改博客文章对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" style="width: 300px"/>
        </el-form-item>
        <el-form-item label="文章概括" prop="summary">
          <el-input v-model="form.summary" placeholder="请输入文章概括" style="width: 300px"/>
        </el-form-item>
        <el-form-item label="优先级" prop="level">
          <el-input-number v-model="form.level" :min="1" label="请输入优先级" style="width: 300px"/>
        </el-form-item>
        <el-form-item label="所属类别" prop="classifyList">
          <el-select v-model="form.classifyList" size="small" placeholder="请选择所属类别"
                     clearable multiple style="width: 300px">
            <el-option
              v-for="item in classifyEnum"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--添加或修改文章内容-->
    <MarkdownEditor ref="markdownEditor" @submitContentForm="submitContentForm"></MarkdownEditor>

    <preview ref="preview"></preview>
  </div>
</template>

<script>
  import {
    addArticle,
    delArticle,
    exportArticle,
    getArticle,
    listArticle,
    updateArticle,
    updateStatus
  } from "@/api/blog/article";
  import {getClassifyEnum} from "@/api/enum"
  import {getContent, updateContent} from '@/api/blog/content'
  import preview from "./preview";

  export default {
    name: "Article",
    components: {preview},
    data() {
      return {
        // 表格渲染回调函数
        // query为gmOptions中配置的query
        callback: (query) => {
          console.log('callback => ', query);
        },
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 博客文章表格数据
        articleList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: undefined,
          summary: undefined,
          level: undefined,
          pollCount: undefined,
          readCount: undefined,
          commentCount: undefined,
          classifyList: [],
          hasDeleted: undefined,
        },
        // 表单参数
        form: {},
      // 表单校验
      rules: {
        title: [
          {required: true, message: "标题不能为空", trigger: "blur"}
        ],
        level: [
          {required: true, message: "优先级不能为空", trigger: "blur"}
        ],
        classifyList: [
          {required: true, message: "所属类别不能为空", trigger: "blur"}
        ],
      },
        //是否删除枚举
        hasDeletedEnum: [{"label": "展示", "value": 0}, {"label": "不展示", "value": 1}],
        classifyEnum: null,

        /*文章内容编辑框*/
        currentId: undefined,
        initialValue: undefined,
      };
  },
  created() {
    this.getList();
    this.getExtData();
  },
  methods: {
    /** 查询博客文章列表 */
    getList() {
      this.loading = true;
      listArticle(this.queryParams).then(response => {
        this.articleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getExtData() {
      getClassifyEnum().then(response => {
        this.classifyEnum = response.data;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        title: undefined,
        summary: undefined,
        level: undefined,
        pollCount: undefined,
        readCount: undefined,
        commentCount: undefined,
        classifyList: [],
        hasDeleted: undefined,
        createTime: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加博客文章";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getArticle(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改博客文章";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateArticle(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addArticle(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除博客文章编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true;
        return delArticle(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
        this.loading = false;
        this.getList();
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有博客文章数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportArticle(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    /**修改是否展示状态*/
    updateHasDeleted(status, row) {
      this.$confirm(`是否确认修改博客文章编号为${row.id}的数据状态为${status === 1 ? `开启` : `关闭`}项?`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true;
        return updateStatus(row.id);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.msgSuccess("修改成功");
      }).catch(() => {
        this.$message.info("已取消");
        if (status === 1) {
          row.hasDeleted = 0;
        } else {
          row.hasDeleted = 1;
        }
      });
    },
    /**查看博客内容*/
    lookContent(id) {
      getContent(id).then(response => {
        if (response.data.content === null || response.data.content === '') {
          this.$refs.preview.openMarkdownPreview(undefined);
        } else {
          this.$refs.preview.openMarkdownPreview(response.data.content);
        }
      })
    },
    /**修改博客内容*/
    updateContent(id) {
      this.currentId = id;
      this.openDrawerDialog(id, '修改内容', false);
    },
    openDrawerDialog(id, title, flag) {
      getContent(id).then(response => {
        if (response.data.content === null || response.data.content === '') {
          this.$refs.markdownEditor.openDrawer(title, flag, undefined);
        } else {
          this.$refs.markdownEditor.openDrawer(title, flag, response.data.content);
        }
      })
    },
    /**关闭文章编辑弹窗*/
    contentCancel() {
      this.contentOpen = false;
    },
    /**提交博客内容*/
    submitContentForm(content) {
      let articleId = this.currentId;
      updateContent({"id": articleId, "content": content}).then(response => {
        if (response.code === 200) {
          this.$message.success("保存成功");
        } else {
          this.$message.error("保存异常");
        }
        this.$refs.markdownEditor.cancel();
      }).catch(error => {
        this.$message.error("保存异常");
        this.$refs.markdownEditor.cancel();
      })
    },
  }
};
</script>
<style scoped>

.tableScopeSwitch {
  margin-right: 5px;
}

.tableScopeSwitch ::v-deep .el-switch__label {
  position: absolute;
  display: none;
  color: #fff;
  font-size: 12px;
}

::v-deep .el-switch.is-checked .el-switch__core::after {
  left: 100%;
  margin-left: -20px;
}

/*打开时文字位置设置*/
.tableScopeSwitch ::v-deep .el-switch__label--right {
  z-index: 1;
  left: 2px; /*不同场景下可能不同，自行调整*/
  height: 23px;
}

.tableScopeSwitch ::v-deep .el-switch__core:after {
  width: 20px;
  height: 20px;
}

/*关闭时文字位置设置*/
.tableScopeSwitch ::v-deep .el-switch__label--left {
  z-index: 1;
  right: 2px; /*不同场景下可能不同，自行调整*/
  height: 23px;
}

/*显示文字*/
.tableScopeSwitch ::v-deep .el-switch__label.is-active {
  display: block;
}

::v-deep.el-switch .is-checked .el-switch__core::after {
  left: 100%;
}

.tableScopeSwitch ::v-deep .el-switch__core,
::v-deep .el-switch {
  width: 65px !important; /*开关按钮的宽度大小*/
  height: 25px;
  line-height: 25px;
  border-radius: 13px;
}


</style>
